package class01;

import java.util.Arrays;

/**
 * 选择排序: 时间复杂度 O(n²) | 空间复杂度 O(1)
 */
public class Code01_SelectionSort {
    public static void main(String[] args) {
        int[] arr = new int[10];
        for (int i = 0; i < arr.length; ++i) {
            arr[i] = (int) (Math.random() * (100 - 1) + 1);
        }
        int[] clone = arr.clone();

        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
        Arrays.sort(clone);
        System.out.println(Arrays.toString(clone));
    }

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; ++i) {
            int minIndex = i;
            for (int j = i + 1; j < arr.length; ++j) {
                minIndex = arr[j] < arr[minIndex] ? j : minIndex;
            }
            swap(arr, i, minIndex);
        }
    }

    public static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}